{% extends 'layout.html' %}

{% block content %}
<div class="container-fluid mt-3">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>超市收银系统</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <style>
           .receipt-scroll {
                scrollbar-width: thin;
                scrollbar-color: #6b7280 #e5e7eb;
            }
           .receipt-scroll::-webkit-scrollbar {
                width: 6px;
            }
           .receipt-scroll::-webkit-scrollbar-track {
                background: #e5e7eb;
            }
           .receipt-scroll::-webkit-scrollbar-thumb {
                background-color: #6b7280;
                border-radius: 3px;
            }
           .product-row:hover {
                background-color: #f3f4f6;
            }
        </style>
    </head>
    <body class="bg-gray-100 font-sans">
        <div class="min-h-screen flex">
            <!-- Left Side - Products -->
            <div class="w-3/5 p-4">
                <div class="bg-white rounded-lg shadow-md p-4 h-full flex flex-col">
                    <h1 class="text-2xl font-bold text-gray-800 mb-4">收银台 - 商品扫描</h1>

                    <div class="flex mb-4">
                        <input 
                            type="text" 
                            id="barcodeInput" 
                            placeholder="扫描条形码或输入商品编号" 
                            class="flex-1 px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            autofocus
                        >
                        <button 
                            id="addProductBtn" 
                            class="bg-blue-600 text-white px-4 py-2 rounded-r-md hover:bg-blue-700 transition"
                        >
                            添加商品
                        </button>
                    </div>

                    <div class="flex space-x-2 mb-4">
                        {% for category in categories %}
                        <button class="product-category bg-{{ category.color }}-100 text-{{ category.color }}-800 px-3 py-1 rounded-md hover:bg-{{ category.color }}-200" data-id="{{ category.id }}">
                            {{ category.name }}
                        </button>
                        {% endfor %}
                    </div>

                    <div class="grid grid-cols-4 gap-3 mb-4" id="productsGrid">
                        {% for product in Product_list %}
                        <button class="product-btn bg-white border border-gray-200 rounded-md p-2 hover:bg-gray-50 transition text-left" 
                                data-id="{{ product.product_code }}" 
                                data-name="{{ product.name }}" 
                                data-price="{{ product.price }}" 
                                data-category="{{ product.category.name }}">
                            <div class="font-medium text-gray-800">{{ product.name }}</div>
                            <div class="text-sm text-gray-500">¥{{ product.price }}</div>
                            <div class="text-xs text-gray-400 mt-1">{{ product.product_code }}</div>
                            <!-- 添加购物车按钮 -->
                            <button class="add-to-cart" data-product-id="{{ product.product_code }}">加入购物车</button>
                        </button>
                        {% endfor %}
                    </div>

                    <div id="scannedProducts" class="overflow-y-auto receipt-scroll flex-1">
                        <div class="border-b border-gray-200 py-2 grid grid-cols-12 font-semibold text-gray-600 text-sm">
                            <div class="col-span-3">商品名称</div>
                            <div class="col-span-2 text-center">单价(元)</div>
                            <div class="col-span-3 text-center">数量</div>
                            <div class="col-span-2 text-center">折扣</div>
                            <div class="col-span-2 text-center">小计(元)</div>
                        </div>
                        <!-- Scanned products will be added here -->
                    </div>
                </div>
            </div>
            <!-- 中间 - 功能菜单 -->
            <!-- <div class="action-column w-1/5 p-4">
                <button class="btn btn-outline-primary w-full" id="increase-btn">+</button>
                <button class="btn btn-outline-primary w-full" id="decrease-btn">-</button>
                <button class="btn btn-outline-danger w-full" id="delete-btn">删除</button>
                <button class="btn btn-outline-warning w-full" id="price-edit-btn">改价</button>
                <button class="btn btn-outline-info w-full" id="item-discount-btn">单品优惠</button>
                <button class="btn btn-outline-secondary w-full" id="return-btn">无单退货</button>
                <button class="btn btn-outline-dark w-full" id="shift-btn">交班</button>
                <button class="btn btn-outline-success w-full" id="member-btn">会员</button>
                <button class="btn btn-outline-success w-full" id="gift-btn">赠送</button>
                <button class="btn btn-outline-warning w-full" id="adjust-price-btn">调价</button>
                <button class="btn btn-outline-info w-full" id="other-btn">其他</button>
            </div> -->

            <!-- Right Side - Payment -->
            <div class="w-2/5 p-4">
                <div class="bg-white rounded-lg shadow-md p-4 h-full flex flex-col">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-xl font-bold text-gray-800">订单详情</h2>
                        <div class="text-sm text-gray-500">收银员: 张三</div>
                    </div>

                    <div id="receiptContainer" class="receipt-scroll overflow-y-auto mb-4 p-3 bg-gray-50 rounded-md border border-gray-200 flex-1">
                        <!-- Receipt content will be displayed here -->
                        <div class="text-center text-gray-500 py-10">等待扫描商品...</div>
                    </div>

                    <div class="bg-gray-100 p-3 rounded-md mb-4 text-sm">
                        <div class="flex justify-between py-1">
                            <span class="text-gray-600">商品总数:</span>
                            <span id="totalQuantity" class="font-semibold">0</span>
                        </div>
                        <div class="flex justify-between py-1">
                            <span class="text-gray-600">总金额:</span>
                            <span id="totalAmount" class="font-semibold">¥0.00</span>
                        </div>
                        <div class="flex justify-between py-1">
                            <span class="text-gray-600">折扣合计:</span>
                            <span id="totalDiscount" class="font-semibold text-red-500">-¥0.00</span>
                        </div>
                        <div class="flex justify-between py-1 border-t border-gray-200 mt-2 pt-2">
                            <span class="text-gray-800 font-bold">应付金额:</span>
                            <span id="payableAmount" class="font-bold text-xl text-blue-600">¥0.00</span>
                        </div>
                    </div>

                    <div class="flex space-x-3 mb-4">
                        <button class="customer-btn flex-1 bg-gray-200 text-gray-800 py-2 rounded-md hover:bg-gray-300">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 inline mr-1" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
                            </svg>
                            会员
                        </button>
                        <button class="coupon-btn flex-1 bg-gray-200 text-gray-800 py-2 rounded-md hover:bg-gray-300">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 inline mr-1" viewBox="0 0 20 20" fill="currentColor">
                                <path d="M2 6a2 2 0 012-2h12a2 2 0 012 2v2a2 2 0 100 4v2a2 2 0 01-2 2H4a2 2 0 01-2-2v-2a2 2 0 100-4V6z" />
                            </svg>
                            优惠券
                        </button>
                        <button class="discount-btn flex-1 bg-gray-200 text-gray-800 py-2 rounded-md hover:bg-gray-300">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 inline mr-1" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M12 1.586l-4 4v12.828l4-4V1.586zM3.707 3.293A1 1 0 002 4v10a1 1 0 00.293.707L6 18.414V5.586L3.707 3.293zM17.707 5.293L14 1.586v12.828l2.293 2.293A1 1 0 0018 16V6a1 1 0 00-.293-.707z" clip-rule="evenodd" />
                            </svg>
                            折扣
                        </button>
                    </div>

                    <div class="grid grid-cols-3 gap-3 mb-4">
                        <button class="payment-method bg-green-100 text-green-800 py-3 rounded-md hover:bg-green-200">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            现金
                        </button>
                        <button class="payment-method bg-blue-100 text-blue-800 py-3 rounded-md hover:bg-blue-200">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                            </svg>
                            银行卡
                        </button>
                        <button class="payment-method bg-yellow-100 text-yellow-800 py-3 rounded-md hover:bg-yellow-200">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                            </svg>
                            手机支付
                        </button>
                    </div>

                    <div class="flex space-x-3">
                        <button id="clearBtn" class="flex-1 bg-red-100 text-red-800 py-3 rounded-md hover:bg-red-200">
                            清除
                        </button>
                        <button id="confirmBtn" class="flex-1 bg-blue-600 text-white py-3 rounded-md hover:bg-blue-700">
                            确认结算
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                // 从 Django 模板上下文获取数据
                const products = [
                    {% for product in Product_list %}
                    {
                        id: '{{ product.product_code }}',
                        name: '{{ product.name }}',
                        price: parseFloat('{{ product.price }}'),
                        category: '{{ product.category.name }}',
                        barcode: '{{ product.barcode }}'  // 假设模型中有 barcode 字段
                    },
                    {% endfor %}
                ];

                const scannedItems = [];
                let totalQuantity = 0;
                let totalAmount = 0;
                let totalDiscount = 0;
                let payableAmount = 0;

                // 初始化产品按钮
                const productGrid = document.querySelector('.grid-cols-4');
                products.forEach(product => {
                    const productBtn = document.createElement('button');
                    productBtn.className = 'product-btn bg-white border border-gray-200 rounded-md p-2 hover:bg-gray-50 transition text-left';
                    productBtn.dataset.id = product.id;
                    productBtn.dataset.name = product.name;
                    productBtn.dataset.price = product.price;
                    productBtn.dataset.category = product.category;

                    productBtn.innerHTML = `
                        <div class="font-medium text-gray-800">${product.name}</div>
                        <div class="text-sm text-gray-500">¥${product.price.toFixed(2)}</div>
                        <div class="text-xs text-gray-400 mt-1">${product.id}</div>
                    `;

                    productBtn.addEventListener('click', function () {
                        addProductToBill(product);
                    });

                    productGrid.appendChild(productBtn);
                });

                // 类别过滤按钮
                const categoryButtons = document.querySelectorAll('.product-category');
                categoryButtons.forEach(button => {
                    button.addEventListener('click', function () {
                        const category = this.textContent;
                        const productButtons = document.querySelectorAll('.product-btn');

                        productButtons.forEach(btn => {
                            if (category === '全部' || btn.dataset.category === category) {
                                btn.style.display = 'block';
                            } else {
                                btn.style.display = 'none';
                            }
                        });
                    });
                });

                // 条形码输入
                const barcodeInput = document.getElementById('barcodeInput');
                const addProductBtn = document.getElementById('addProductBtn');

                barcodeInput.addEventListener('keypress', function (e) {
                    if (e.key === 'Enter') {
                        addProductByBarcode();
                    }
                });

                addProductBtn.addEventListener('click', addProductBy
                function addProductByBarcode() {
                    const input = barcodeInput.value.trim();
                    if (!input) return;

                    let foundProduct = null;

                    // First try ID match
                    foundProduct = products.find(p => p.id === input);

                    // Then try barcode match
                    if (!foundProduct) {
                        foundProduct = products.find(p => p.barcode === input);
                    }

                    if (foundProduct) {
                        addProductToBill(foundProduct);
                        barcodeInput.value = '';
                        barcodeInput.focus();
                    } else {
                        alert('未找到匹配的商品！');
                    }
                }

                function addProductToBill(product) {
                    const existingItem = scannedItems.find(item => item.id === product.id);

                    if (existingItem) {
                        existingItem.quantity += 1;
                        existingItem.subtotal = existingItem.quantity * existingItem.price;
                    } else {
                        scannedItems.push({
                            id: product.id,
                            name: product.name,
                            price: product.price,
                            quantity: 1,
                            discount: 0,
                            subtotal: product.price
                        });
                    }

                    updateBillDisplay();
                }

                function updateBillDisplay() {
                    // Update scanned products list
                    const scannedProductsDiv = document.getElementById('scannedProducts');
                    scannedProductsDiv.innerHTML = `
                        <div class="border-b border-gray-200 py-2 grid grid-cols-12 font-semibold text-gray-600 text-sm">
                            <div class="col-span-3">商品名称</div>
                            <div class="col-span-2 text-center">单价(元)</div>
                            <div class="col-span-3 text-center">数量</div>
                            <div class="col-span-2 text-center">折扣</div>
                            <div class="col-span-2 text-center">小计(元)</div>
                        </div>
                    `;

                    totalQuantity = 0;
                    totalAmount = 0;
                    totalDiscount = 0;

                    scannedItems.forEach(item => {
                        const itemRow = document.createElement('div');
                        itemRow.className = 'product-row border-b border-gray-200 py-2 grid grid-cols-12 text-sm';

                        itemRow.innerHTML = `
                            <div class="col-span-3 font-medium">${item.name}</div>
                            <div class="col-span-2 text-center">¥${item.price.toFixed(2)}</div>
                            <div class="col-span-3 flex items-center justify-center">
                                <button class="quantity-btn decrease w-6 h-6 rounded-l bg-gray-200 hover:bg-gray-300" data-id="${item.id}">-</button>
                                <span class="quantity w-10 text-center border-t border-b border-gray-200">${item.quantity}</span>
                                <button class="quantity-btn increase w-6 h-6 rounded-r bg-gray-200 hover:bg-gray-300" data-id="${item.id}">+</button>
                            </div>
                            <div class="col-span-2 text-center text-red-500">${item.discount > 0? `-¥${item.discount.toFixed(2)}` : '-'}</div>
                            <div class="col-span-2 text-center font-medium">¥${item.subtotal.toFixed(2)}</div>
                        `;

                        scannedProductsDiv.appendChild(itemRow);

                        totalQuantity += item.quantity;
                        totalAmount += item.subtotal + item.discount;
                        totalDiscount += item.discount;
                    });

                    payableAmount = totalAmount - totalDiscount;

                    // Update receipt display
                    const receiptContainer = document.getElementById('receiptContainer');
                    receiptContainer.innerHTML = `
                        <div class="text-center font-bold mb-4">超市收银小票</div>
                        <div class="text-center text-xs mb-4">${new Date().toLocaleString()}</div>
                        <div class="text-center text-xs mb-4">收银员: 张三</div>
                        <div class="border-t border-b border-gray-200 py-2 grid grid-cols-12 text-xs font-medium">
                            <div class="col-span-6">商品</div>
                            <div class="col-span-2 text-right">单价</div>
                            <div class="col-span-2 text-right">数量</div>
                            <div class="col-span-2 text-right">小计</div>
                        </div>
                    `;

                    scannedItems.forEach(item => {
                        const receiptItem = document.createElement('div');
                        receiptItem.className = 'py-1 grid grid-cols-12 text-xs border-b border-gray-100';

                        receiptItem.innerHTML = `
                            <div class="col-span-6 truncate">${item.name}</div>
                            <div class="col-span-2 text-right">${item.price.toFixed(2)}</div>
                            <div class="col-span-2 text-right">${item.quantity}</div>
                            <div class="col-span-2 text-right">${item.subtotal.toFixed(2)}</div>
                        `;

                        if (item.discount > 0) {
                            const discountRow = document.createElement('div');
                            discountRow.className = 'col-span-12 text-right text-xs text-red-500';
                            discountRow.textContent = `优惠: -${item.discount.toFixed(2)}`;
                            receiptItem.appendChild(discountRow);
                        }

                        receiptContainer.appendChild(receiptItem);
                    });

                    receiptContainer.innerHTML += `
                        <div class="mt-4 text-sm">
                            <div class="flex justify-between py-1">
                                <span>商品总数:</span>
                                <span>${totalQuantity}</span>
                            </div>
                            <div class="flex justify-between py-1">
                                <span>总金额:</span>
                                <span>¥${totalAmount.toFixed(2)}</span>
                            </div>
                            <div class="flex justify-between py-1 text-red-500">
                                <span>优惠:</span>
                                <span>-¥${totalDiscount.toFixed(2)}</span>
                            </div>
                            <div class="flex justify-between py-1 font-bold border-t border-gray-200 mt-1 pt-1">
                                <span>应付金额:</span>
                                <span>¥${payableAmount.toFixed(2)}</span>
                            </div>
                        </div>
                        <div class="text-xs text-center mt-6">
                            谢谢惠顾，欢迎下次光临
                        </div>
                    `;

                    // Update summary
                    document.getElementById('totalQuantity').textContent = totalQuantity;
                    document.getElementById('totalAmount').textContent = `¥${totalAmount.toFixed(2)}`;
                    document.getElementById('totalDiscount').textContent = `-¥${totalDiscount.toFixed(2)}`;
                    document.getElementById('payableAmount').textContent = `¥${payableAmount.toFixed(2)}`;

                    // Add event listeners for quantity buttons
                    document.querySelectorAll('.quantity-btn.decrease').forEach(btn => {
                        btn.addEventListener('click', function () {
                            const productId = this.dataset.id;
                            const item = scannedItems.find(i => i.id === productId);

                            if (item.quantity > 1) {
                                item.quantity -= 1;
                                item.subtotal = item.quantity * item.price - item.discount;
                                updateBillDisplay();
                            }
                        });
                    });

                    document.querySelectorAll('.quantity-btn.increase').forEach(btn => {
                        btn.addEventListener('click', function () {
                            const productId = this.dataset.id;
                            const item = scannedItems.find(i => i.id === productId);

                            item.quantity += 1;
                            item.subtotal = item.quantity * item.price - item.discount;
                            updateBillDisplay();
                        });
                    });
                }

                // Clear button
                document.getElementById('clearBtn').addEventListener('click', function () {
                    if (scannedItems.length === 0) return;
                    if (confirm('确定要清空当前购物列表吗？')) {
                        scannedItems.length = 0;
                        updateBillDisplay();
                        barcodeInput.focus();
                    }
                });

                // Payment methods
                document.querySelectorAll('.payment-method').forEach(btn => {
                    btn.addEventListener('click', function () {
                        if (scannedItems.length === 0) {
                            alert('请先添加商品！');
                            return;
                        }

                        let paymentMethod = this.textContent.trim();
                        alert(`已选择${paymentMethod}支付，应付金额: ¥${payableAmount.toFixed(2)}`);
                        // Here you would typically redirect to payment gateway or open a modal
                    });
                });

                // Enhanced checkout with pending orders
                const pendingOrders = [];

                // Save pending order button
                document.getElementById('shift-btn').addEventListener('click', function () {
                    if (scannedItems.length === 0) {
                        alert('请先添加商品！');
                        return;
                    }

                    const orderName = prompt('请输入挂单名称:');
                    if (orderName) {
                        pendingOrders.push({
                            name: orderName,
                            items: [...scannedItems],
                            total: payableAmount
                        });
                        scannedItems.length = 0;
                        updateBillDisplay();
                        alert(`挂单"${orderName}"已保存`);
                    }
                });

                // Restore pending order button
                document.getElementById('other-btn').addEventListener('click', function () {
                    if (pendingOrders.length === 0) {
                        alert('没有可恢复的挂单');
                        return;
                    }

                    const orderList = pendingOrders.map((order, index) => 
                        `${index+1}. ${order.name} (¥${order.total.toFixed(2)})`).join('\n');
                    const choice = parseInt(prompt(`选择要恢复的挂单:\n${orderList}`));

                    if (choice > 0 && choice <= pendingOrders.length) {
                        scannedItems.length = 0;
                        pendingOrders[choice-1].items.forEach(item => {
                            scannedItems.push({...item});
                        });
                        updateBillDisplay();
                        alert(`挂单"${pendingOrders[choice-1].name}"已恢复`);
                    }
                });

                // Confirm button with AJAX checkout
                document.getElementById('confirmBtn').addEventListener('click', function () {
                    if (scannedItems.length === 0) {
                        alert('请先添加商品！');
                        return;
                    }

                    fetch('/checkout/', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': '{{ csrf_token }}'
                        },
                        body: JSON.stringify({
                            items: scannedItems,
                            total: payableAmount
                        })
                    })
                   .then(response => response.json())
                   .then(data => {
                        if (data.success) {
                            alert(`结算完成！订单号: ${data.order_id}\n应付金额: ¥${payableAmount.toFixed(2)}`);
                            scannedItems.length = 0;
                            updateBillDisplay();
                        } else {
                            alert('结算失败: ' + data.message);
                        }
                    });
                });

                // Enhanced member discount system
                document.querySelector('.customer-btn').addEventListener('click', function () {
                    const memberId = prompt('请输入会员卡号:');
                    if (memberId) {
                        fetch(`/apply_member_discount/?member_id=${memberId}`)
                           .then(response => response.json())
                           .then(data => {
                                if (data.status) {
                                    // Apply member discount to all items
                                    scannedItems.forEach(item => {
                                        item.discount = item.price * item.quantity * data.discount_rate;
                                        item.subtotal = (item.price * item.quantity) - item.discount;
                                    });
                                    updateBillDisplay();
                                    alert(`会员卡号 ${memberId} 已关联\n已应用${data.discount_rate*100}%会员折扣`);
                                } else {
                                    alert(data.message);
                                }
                            });
                    }
                });

                // Enhanced coupon system
                document.querySelector('.coupon-btn').addEventListener('click', function () {
                    const couponCode = prompt('请输入优惠券码:');
                    if (couponCode) {
                        fetch(`/apply_coupon/?coupon_code=${couponCode}`)
                           .then(response => response.json())
                           .then(data => {
                                if (data.status) {
                                    // Apply coupon to eligible items
                                    scannedItems.forEach(item => {
                                        if (data.eligible_products.includes(item.id)) {
                                            item.discount = item.price * item.quantity * data.discount_rate;
                                            item.subtotal = (item.price * item.quantity) - item.discount;
                                        }
                                    });
                                    updateBillDisplay();
                                    alert(`优惠券 ${couponCode} 已应用\n${data.discount_rate*100}折优惠已生效`);
                                } else {
                                    alert(data.message);
                                }
                            });
                    }
                });

                document.querySelector('.discount-btn').addEventListener('click', function () {
                    if (scannedItems.length === 0) {
                        alert('请先添加商品！');
                        return;
                    }

                    const productId = prompt('请输入要打折的商品ID:');
                    if (!productId) return;

                    const item = scannedItems.find(i => i.id === productId);
                    if (!item) {
                        alert('未找到该商品！');
                        return;
                    }

                    const discountAmount = parseInt(prompt(`请输入优惠金额 (${item.name} 原价: ¥${item.price.toFixed(2)})`));
                    if (!isNaN(discountAmount) && discountAmount > 0) {
                        item.discount = discountAmount;
                        item.subtotal = (item.price * item.quantity) - discountAmount;
                        updateBillDisplay();
                    }
                });

                // Focus barcode input on page load
                barcodeInput.focus();
            });
        </script>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const products = [
                    {% for product in Product_list %}
                    {
                        id: '{{ product.product_code }}',
                        name: '{{ product.name }}',
                        price: parseFloat('{{ product.price }}'),
                        category: '{{ product.category.name }}',
                        barcode: '{{ product.barcode }}'
                    },
                    {% endfor %}
                ];

                let cart = [];

                function addToCart(productId) {
                    const product = products.find(p => p.id === productId);
                    if (product) {
                        const cartItem = cart.find(item => item.id === productId);
                        if (cartItem) {
                            cartItem.quantity++;
                        } else {
                            cart.push({...product, quantity: 1 });
                        }
                    }
                    updateCartDisplay();
                }

                function updateCartDisplay() {
                    const cartDisplay = document.getElementById('cartDisplay');
                    cartDisplay.innerHTML = '';
                    let totalQuantity = 0;
                    let totalAmount = 0;
                    cart.forEach(item => {
                        totalQuantity += item.quantity;
                        totalAmount += item.price * item.quantity;
                        const cartItem = document.createElement('div');
                        cartItem.innerHTML = `
                            <p>${item.name} - ¥${item.price.toFixed(2)} x ${item.quantity}</p>
                        `;
                        cartDisplay.appendChild(cartItem);
                    });
                    const totalDisplay = document.getElementById('totalDisplay');
                    totalDisplay.innerHTML = `
                        <p>总数量: ${totalQuantity}</p>
                        <p>总金额: ¥${totalAmount.toFixed(2)}</p>
                    `;
                }

                document.querySelectorAll('.add-to-cart').forEach(button => {
                    button.addEventListener('click', function () {
                        const productId = this.getAttribute('data-product-id');
                        addToCart(productId);
                    });
                });

                // 初始化购物车显示区域
                const cartDisplay = document.createElement('div');
                cartDisplay.id = 'cartDisplay';
                document.body.appendChild(cartDisplay);

                const totalDisplay = document.createElement('div');
                totalDisplay.id = 'totalDisplay';
                document.body.appendChild(totalDisplay);
            });
        </script>
    </body>
{% endblock %}